package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

var (
	g_cmd      string
	g_code     string
	g_dst_path string
	g_cycle    int
	g_days     int
	dstPath    string = "/tmp/.stock"
)

func init() {
	err := os.MkdirAll(dstPath, os.ModePerm)
	if err != nil {
		panic(fmt.Sprintf("You should be able to create the directory for goml model persistance testing.\n\tError returned: %v\n", err.Error()))
	}
	flag.StringVar(&g_cmd, "cmd", "download", "首命令")
	flag.StringVar(&g_code, "code", "sh510050", "stock code")
	flag.StringVar(&g_dst_path, "dst_path", "/tmp/stock_ai", "目的目录")
	flag.IntVar(&g_cycle, "cycle", 5, "周期")
	flag.IntVar(&g_days, "days", 10, "天数")
}

func main() {
	flag.Parse()

	switch g_cmd {
	case "download":
		do_download()
	}
}

func do_download() {
	url := fmt.Sprintf("https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=%s&scale=%d&ma=no&datalen=%d", g_code, g_cycle, g_days*(240/g_cycle))
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("NewRequest failed")
		return
	}
	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("client do failed", err)
		return
	}
	defer resp.Body.Close()

	byte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("ioutil readall err", err)
		return
	}

	obj := []StockRecord{}
	err = json.Unmarshal(byte, &obj)
	if err != nil {
		fmt.Println("json unmarshal failed", err)
		return
	}
	fmt.Println("num=", len(obj))
}

type StockRecord struct {
	Open   string `json:"open"`
	Close  string `json:"close"`
	High   string `json:"high"`
	Low    string `json:"low"`
	Volume string `json:"volume"`
}
